package com.emm.yixun.system.service.impl;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jws.WebService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.common.exception.ResponseCode;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.basic.service.UserService;
import com.emm.yixun.basic.service.UserTokenService;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.UserToken;
import com.emm.yixun.common.model.dto.UserDto;
import com.emm.yixun.common.model.dto.UserTokenDto;
import com.emm.yixun.common.model.enums.DeviceTypeEnum;
import com.emm.yixun.common.model.enums.StatusEnum;
import com.emm.yixun.system.service.UserTokenServiceFacade;

@Service
@WebService(name="com.emm.yixun.system.service.UserTokenServiceFacade")
public class UserTokenServiceFacadeImpl implements UserTokenServiceFacade{
	private  final Logger   logger = LoggerFactory.getLogger(this.getClass()); 
	
	private static Map<String,String> reLoginMap;
	
	static{
		reLoginMap=new HashMap<String,String>();
	}
	
	@Autowired
	private UserTokenService service;
	
	@Autowired
	private UserService userService;

	@Override
	public Response<UserTokenDto> save(UserTokenDto dto) {
		Response<UserTokenDto> response=new Response<UserTokenDto>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			UserTokenDto mDto=service.create(dto);
			if(null==mDto){
				response.fail("80000", "保存数据错误");
				return response;
			}
			response.success(mDto);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<Integer> updateByPrimaryKey(UserTokenDto dto,Boolean selective) {
		Response<Integer> response=new Response<Integer>();
		try {
			if(null==selective || null==dto || null==dto.getId()){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("更新"));
				return response;
			}
			
			if(selective){
				int count=service.update(dto);
				if(count>0){
					response.success(Integer.valueOf(count));
				}else{
					response.fail("90001", "更新数据失败");
				}
			}else{
				response.fail("90000", "暂未实现,修改参数selective=true即可");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<Integer> deleteByPrimaryKey(Long id) {
		Response<Integer> response=new Response<Integer>();
		try {
			if(null==id){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("删除"));
				return response;
			}
			UserTokenDto mDto=new UserTokenDto();
			mDto.setId(id);
			int count=service.destroy(mDto);
			if(count>0){
				response.success(Integer.valueOf(count));
			}else{
				response.fail("90001", "删除数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("删除数据错误：{}",e);
		}
		return response;
	}
	
    @Override
	public Response<UserToken> findById(Long id) {
		Response<UserToken> response=new Response<UserToken>();
		try {
			if(null==id){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			UserToken entity=service.selectById(id);
			if(null==entity){
				response.fail("90001", "主键查询数据失败");
			}else{
				response.success(entity);;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}",e);
		}
		return response;
	}

	@Override
	public ResponseList<UserToken> findByDto(UserTokenDto dto) {
		ResponseList<UserToken> response=new ResponseList<UserToken>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<UserToken> list=service.selectListByDto(dto);
			if(null==list){
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Page<UserToken> findPageByDto(UserTokenDto dto, Integer begin,Integer row) {
		Page<UserToken> response=new Page<UserToken>();
		try {
			if(null==dto || null==begin || null==row){
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<UserToken> page = service.getPageModel(dto, begin, row);
			if(null==page.getRows()){
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response=page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<Boolean> createUserToken(Long userId,Long merchantId) {
		Response<Boolean> response=new Response<Boolean>();
		try {
			if(null==userId || null==merchantId){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存用户token"));
				return response;
			}
			UserTokenDto userTokenDto=new UserTokenDto();
			userTokenDto.setUserId(userId);
			userTokenDto.setDeviceType(DeviceTypeEnum.PC.getNo());
			userTokenDto.setMerchantId(String.valueOf(merchantId));
			UserToken userToken=service.selectByDto(userTokenDto);
			if(null==userToken){
				userTokenDto.setStatus(StatusEnum.TOLOGIN.getNo());
				userTokenDto.setCreateUserId(userId);
				userTokenDto.setUpdateUserId(userId);
				userTokenDto.setDelFlag("0");
				userTokenDto.setCreateTime(new Date());
				userTokenDto.setUpdateTime(new Date());
				UserTokenDto mDto=service.create(userTokenDto);
				if(null==mDto){
					response.fail("80000", "保存用户token错误");
					return response;
				}
			}else{
				UserTokenDto updateDto=new UserTokenDto();
				updateDto.setId(userToken.getId());
				updateDto.setStatus(StatusEnum.TOLOGIN.getNo());
				int updateCount=service.update(updateDto);
				if(updateCount<=0){
					response.fail("80000", "保存用户token错误");
					return response;
				}
			}
			response.success(true);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存用户token错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<Boolean> reLoginCheck(String userId) {
		// TODO Auto-generated method stub
		Response<Boolean> response=new Response<Boolean>();
		boolean isReLogin=reLoginMap.containsKey(userId);
		response.success(isReLogin);
		return response;
	}

	@Override
	public Response<Boolean> addReLogin(String roleId) {
		Response<Boolean> response=new Response<Boolean>();
		UserDto ud=new UserDto();
		ud.setRoleId(Long.valueOf(roleId));
		List<User> roleUserList=userService.selectListByDto(ud);
		if(null!=roleUserList){
			for(User user : roleUserList){
				String userId=String.valueOf(user.getId());
				reLoginMap.put(String.valueOf(user.getId()), userId);
			}
		}
		response.success(true);
		return response;
	}

	@Override
	public Response<Boolean> removeReLogin(String userId) {
		Response<Boolean> response=new Response<Boolean>();
		reLoginMap.remove(userId);
		response.success(true);
		return response;
	}

	@Override
	public Response<Boolean> addRoleAndUserLogin(String roleId, String userId) {
		Response<Boolean> response=new Response<Boolean>();
		UserDto ud=new UserDto();
		ud.setRoleId(Long.valueOf(roleId));
		ud.setId(Long.valueOf(userId));
		User roleUser=userService.selectByDto(ud);
		if(null!=roleUser){
				String uid=String.valueOf(roleUser.getId());
				reLoginMap.put(String.valueOf(roleUser.getId()), uid);
		}
		response.success(true);
		return response;
	}

}
